import React, { useEffect, useState } from 'react'
import servicer from '../../api/servicer'
import { Banner, Button, Card, Col, Dropdown, Input, Row, Spin, Tag, TagInput, Toast } from '@douyinfe/semi-ui'
import { notificationCatchErr } from '../../lib/utils'

export default function AutoReplyComment() {
    const [items, setItems] = useState([])
    const [loading, setLoading] = useState(false);

    React.useEffect(() => {
        setLoading(true)
        servicer.listAutoReplyComment().then(({ data }) => {
            setLoading(false)
            setItems(data)
        })
    }, [])

    const handleChange = (tags, index) => {
        items[index].tags = tags
        setItems([...items])
    }

    const updateItems = (index, item, check = false) => {
        items[index] = item
        if (check) {
            item.editable = true;
            // if (!item.name) return toast.error('分组名称必须填写')
            // if (!item.tags.length) return toast.error('评论关键词必须填写')
            // if (!item.comment.length) return toast.error('回复内容必须填写')

            // for (let i = 0; i < item.tags.length; i++) {
            //     if (item.tags[i].trim() === '') return toast.error('评论关键词必须填写')
            // }
            setLoading(true)
            servicer.setAutoReplyComment(item).then(({ data }) => {
                setLoading(false)
                item.id = data.id
                items[index] = item
                item.editable = false;
                setItems([...items])
            })

        } else {
            setItems([...items])
        }
    };

    const deleteItems = (index) => {
        const item = items.splice(index, 1)
        if (item[0].id) {
            setLoading(true)
            servicer.deleteAutoReplyComment({ id: item[0].id }).then(() => {
                setLoading(false)
                setItems([...items])
            }).catch(notificationCatchErr("删除失败"))
        }
    }


    return <>
        <Spin spinning={loading}>

            <Banner
                fullMode={false}
                type="info"
                bordered
                title={<div style={{ fontWeight: 600, fontSize: '14px', lineHeight: '20px' }}>自动回评</div>}
                description={<div>提前编辑好公屏回复话术，在直播时可自动匹配并回复用户评论，最多创建20组</div>}
                closeIcon={null}
            >
                <Button style={{ float: 'right', position: 'relative', top: '-42px' }}
                    onClick={() => {
                        if (items.length >= 20) {
                            return Toast.error('最多添加20组评论');
                        }

                        for (let i = 0; i < items.length; i++) {
                            if (!items[i].id) return Toast.error('未提交的回复组(序号' + (i + 1) + ')，无法添加新的回复组');
                        }

                        const _items = [...items, {
                            name: '新回复组',
                            tags: [],
                            comment: '',
                            editable: true
                        }]

                        setItems(_items)
                    }}
                >新回复组</Button>
            </Banner>



            <div className='grid gap-4 sm:grid-cols-1'>
                {
                    items.map((item, index) => (
                        <Card
                            key={'autoReplyComment' + index}
                            style={{ marginTop: '10px', width: '100%' }}
                            title={null}
                            headerLine={false}

                        >
                            <Row>
                                <Col span={16}>
                                    <Input value={item.name}
                                        disabled={!item.editable}
                                        onInput={(event) => {
                                            item.name = event.target.value
                                            updateItems(index, item)
                                        }} style={{ display: 'inline-block', width: '160px' }} />
                                </Col>
                                <Col span={8} style={{ textAlign: 'right' }}>
                                    <Dropdown
                                        style={{ float: 'right' }}
                                        render={
                                            <Dropdown.Menu>
                                                {
                                                    item.editable ?
                                                        <Dropdown.Item onClick={
                                                            () => { item.editable = false; updateItems(index, item, true) }
                                                        }>保存</Dropdown.Item> :
                                                        <Dropdown.Item onClick={
                                                            () => { item.editable = true; updateItems(index, item) }
                                                        }>编辑</Dropdown.Item>
                                                }
                                                <Dropdown.Item onClick={() => deleteItems(index)}>删除 </Dropdown.Item>
                                            </Dropdown.Menu>
                                        }
                                    >
                                        <Button>操作</Button>
                                    </Dropdown>
                                </Col>
                            </Row>

                            <div className="flex w-full items-center space-x-2 auto-comment-item" style={{ margin: '10px 0' }}>
                                <TagInput
                                    defaultValue={item.tags}
                                    disabled={!item.editable}
                                    placeholder='评论关键词'
                                    onChange={tags => handleChange(tags, index)}
                                />
                            </div>

                            <div className="flex w-full items-center space-x-2 auto-comment-item">
                                <Input disabled={!item.editable}
                                    value={item.comment}
                                    onInput={(event) => {
                                        item.comment = event.target.value
                                        updateItems(index, item)
                                    }}
                                    placeholder="回复内容,如: 稍后绘发送优惠券哟✌" />
                            </div>

                        </Card>

                    ))
                }
            </div>

        </Spin>

    </>
}
